package com.alien.admin.modules.security.service;

import com.alien.admin.modules.security.service.dto.JwtUserDto;
import com.alien.admin.modules.system.service.RoleService;
import com.alien.admin.utils.RedisUtils;
import com.alien.admin.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author: alien.guo
 * @date: 2020/12/24
 */
@Component
public class UserCacheClean {

    @Autowired
    private RoleService roleService;
    @Autowired
    private RedisUtils redisUtils;

    public String getUserEnv(String userName) {
        String envKey = String.format("env:%s", userName);
        String env = (String)redisUtils.get(envKey);
        return env;
    }

    public void setUserEnv(String userName, String env) {
        String envKey = String.format("env:%s", userName);
        redisUtils.set(envKey, env);
    }

    /**
     * 清理特定用户缓存信息<br>
     * 用户信息变更时
     *
     * @param userName /
     */
    public void cleanUserCache(String userName) {
        if (StringUtils.isNotEmpty(userName)) {
            UserDetailsServiceImpl.userDtoCache.remove(userName);
        }
    }

    /**
     * 清理所有用户的缓存信息<br>
     * ,如发生角色授权信息变化，可以简便的全部失效缓存
     */
    public void cleanAll() {
        UserDetailsServiceImpl.userDtoCache.clear();
    }

    /**
     * 由於权限与环境关联，提供刷新权限信息接口
     */
    public void refreshRolesAuthorities(String userName, String env) {
        JwtUserDto jwtUserDto = UserDetailsServiceImpl.userDtoCache.get(userName);
        if(jwtUserDto != null) {
            List<GrantedAuthority> grantedAuthorities = roleService.mapToGrantedAuthorities(jwtUserDto.getUser(), env);
            jwtUserDto.setAuthorities(grantedAuthorities);
            UserDetailsServiceImpl.userDtoCache.put(userName, jwtUserDto);
        }
    }
}
